package org.tangolyricstagger.gui;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Map;
import java.util.Properties;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.beanutils.BeanUtils;

@Slf4j
public class SettingsManager {
	private Properties properties = new Properties();
	@Getter
	private Settings settings = new Settings();

	private File file;
	private File myPath = new File(System.getProperty("user.home") + "/.TangoLyricsTagger");

	public SettingsManager() {
	}

	public boolean loadSettings() {
		file = new File(myPath, "settings.ini");
		if (file.exists()) {
			try {
				FileReader fr = new FileReader(file);
				properties.load(fr);
				BeanUtils.populate(settings, properties);
			} catch (Exception e) {
				log.error("can't read settings", e);
			}
			return true;
		} else {
			return false;
		}

	}

	@SuppressWarnings("unchecked")
	public void writeSettings() {
		try {
			// PropertyUtils.copyProperties(properties, this);
			Map<String, String> propertiesAsMap = BeanUtils.describe(settings);
			propertiesAsMap.remove("class");
			properties.putAll(propertiesAsMap);
			if (!myPath.exists()) {
				myPath.mkdir();
			}
			FileWriter fw = new FileWriter(file);
			properties.store(fw, "");
			fw.flush();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
